package com.wangzg.module.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wangzg.common.util.Constants;
import com.wangzg.common.util.CoreConst;
import com.wangzg.common.util.Pagination;
import com.wangzg.common.util.ResultUtil;
import com.wangzg.module.admin.model.kuaidi.KuaiDi;
import com.wangzg.module.admin.service.KuaiDiService;
import com.wangzg.module.admin.vo.base.PageResultVo;
import com.wangzg.module.admin.vo.base.ResponseVo;

import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RequestMapping("kuaidi")
@Controller
public class KuaiDiController {

    @Autowired
    private KuaiDiService kuaiDiService;


    @PostMapping("/getList")
    @ResponseBody
    public PageResultVo loadKuaidis(KuaiDi kuaiDi, Integer pageNumber, Integer pageSize) {
        IPage<KuaiDi> page = new Pagination<>(pageNumber, pageSize);
        List<KuaiDi> articleList = kuaiDiService.findByCondition(page, kuaiDi);
        return ResultUtil.table(articleList, page.getTotal());
    }
    @PostMapping("/addKuaiDi")
    public @ResponseBody
    ResponseVo addKuaiDi(String userName, String phone, String kuaiDiNo, String company) {
        kuaiDiService.add(userName, phone, kuaiDiNo, company);
        return ResultUtil.success("添加快递信息成功");
    }


    @PostMapping("/delKuaiDi")
    public @ResponseBody
    ResponseVo delKuaiDi(Integer id) {
        kuaiDiService.removeById(id);
        return ResultUtil.success("删除快递信息成功");

    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("batch/delete")
    public @ResponseBody
    ResponseVo batchDelete(@RequestParam("ids[]") List<String> ids) {
        kuaiDiService.removeByIds(ids);
        return ResultUtil.success("删除快递信息成功");

    }
    /**
     * 编辑快递详情
     */
    @GetMapping("/edit")
    public String userDetail(Model model, String id) {
        KuaiDi kuaiDi = kuaiDiService.selectById(id);
        model.addAttribute("kuaidi", kuaiDi);
        return CoreConst.ADMIN_PREFIX + "kuaidi/kuaiDiDetail";
    }

    @PostMapping("/modifyKuaiDi")
    public @ResponseBody
    ResponseVo modifyKuaiDi(KuaiDi kuaiDi) {
        kuaiDiService.modify(kuaiDi);
        return ResultUtil.success("修改快递信息成功");
    }


    @RequestMapping("template/download")
    public ResponseEntity<byte[]> download() throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Resource resource = new ClassPathResource("excelTemplate" + File.separator + "kuaidi.xls");
        InputStream fis =resource.getInputStream();
        IOUtils.copy(fis, out);
        HttpHeaders headers = new HttpHeaders();
        String fileName = new String(Constants.DOWNLOAD_EXCEL_TEMPLATE_NAME.getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> filebyte = new ResponseEntity<byte[]>(out.toByteArray(),headers, HttpStatus.CREATED);
        try {
            out.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filebyte;
    }

    @PostMapping("/import")
    @ResponseBody
    public ResponseVo importData(MultipartFile file) throws Exception {
        kuaiDiService.importData(file);
        return ResultUtil.success("批量导入快递信息成功");
    }

    @PostMapping("/export")
    @ResponseBody
    public void exportData(@RequestParam("ids[]") List<String> ids,  HttpServletResponse response) throws Exception{
//        kuaiDiService.exportData(ids); https://hutool.cn/docs/#/poi/Excel%E7%94%9F%E6%88%90-ExcelWriter
        Map<String, Object> row1 = new LinkedHashMap<>();
        row1.put("姓名", "张三");
        row1.put("年龄", 23);
        row1.put("成绩", 88.32);
        row1.put("是否合格", true);
        row1.put("考试日期", DateUtil.date());

        Map<String, Object> row2 = new LinkedHashMap<>();
        row2.put("姓名", "李四");
        row2.put("年龄", 33);
        row2.put("成绩", 59.50);
        row2.put("是否合格", false);
        row2.put("考试日期", DateUtil.date());

        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1, row2);
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        //out为OutputStream，需要写出到的目标流

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename=test.xls");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

    @GetMapping("/export")
    @ResponseBody
    public void exportDataByGet(String userName, String phone, HttpServletResponse response) throws Exception{

        ArrayList<Map<String, Object>> excelRows = CollUtil.newArrayList();

        List<KuaiDi> kuaiDiList = kuaiDiService.list(
                new LambdaQueryWrapper<KuaiDi>()
                .eq(StringUtils.isNotBlank(userName), KuaiDi::getUserName, userName)
                .eq(StringUtils.isNotBlank(phone), KuaiDi::getPhone, phone)
        );
        if(CollUtil.isNotEmpty(kuaiDiList)){
            kuaiDiList.stream().forEach(k -> {
                Map<String, Object> tempRow = new LinkedHashMap<String, Object>(){{
                    put(Constants.EXCEL_HEADER_ALIAS_LIST.get(0), k.getKuaidiNo());
                    put(Constants.EXCEL_HEADER_ALIAS_LIST.get(1), k.getUserName());
                    put(Constants.EXCEL_HEADER_ALIAS_LIST.get(2), k.getPhone());
                    put(Constants.EXCEL_HEADER_ALIAS_LIST.get(3), k.getCompany());
                }};
                excelRows.add(tempRow);
            });


        }

        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(excelRows, true);
        //out为OutputStream，需要写出到的目标流

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename=kuaidi.xls");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
}
